import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com', // 替换为你的API基础URL
  timeout: 10000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response.data;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 404:
          console.error('Resource not found:', error.response.data);
          break;
        case 401:
          console.error('Unauthorized access:', error.response.data);
          // 这里可以添加重定向到登录页面的逻辑
          break;
        default:
          console.error('Error:', error.response.status, error.response.data);
      }
    } else if (error.request) {
      console.error('No response received:', error.request);
    } else {
      console.error('Request setup failed:', error.message);
    }
    return Promise.reject(error);
  }
);

export const get = async (url, params = {}) => {
  try {
    const response = await instance.get(url, { params });
    return response;
  } catch (error) {
    throw error;
  }
};

export const post = async (url, data = {}, headers = {}) => {
  try {
    const response = await instance.post(url, data, { headers });
    return response;
  } catch (error) {
    throw error;
  }
};

export const uploadFile = async (url, file, onUploadProgress = null) => {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await instance.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: onUploadProgress ? event => {
        onUploadProgress(Math.round((event.loaded * 100) / event.total));
      } : undefined,
    });
    return response;
  } catch (error) {
    throw error;
  }
};



